package com.chorye.datasource.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Company: 北京XXXX有限公司
 * @Author JiangYy
 * @Title: DruidConfig
 * @Description: TODO
 * @Date 2018/12/12 13:39
 */
@Configuration
@MapperScan("com.chorye.datasource.dao")
public class DruidConfig {

    /**
     * 简单的配置druid数据库连接池
     *
     * @return druid数据库连接池
     */
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }

    /**
     * 配置一个管理后台的Servlet
     *
     * @return 管理后台的Servlet
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        // 拦截所有/druid/的路径请求
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>(4);
        // 登录druid监控的账户
        initParams.put("loginUsername", "chorye");
        // 登录druid监控的密码
        initParams.put("loginPassword", "chorye");
        // 默认就是允许所有访问
        initParams.put("allow", "");
        // 黑名单的IP
        initParams.put("deny", "");
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置一个web监控的filter
     *
     * @return web监控的filter
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<>(1);
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}
